package com.eascs.credit.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.credit.entity.CreditReport;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.dao.O2oLoanUserDao;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.DateUtils;
import com.eascs.credit.dao.O2oCreditDao;
import com.eascs.credit.dao.OaDatalistDao;
import com.eascs.credit.entity.CreditResolve;
import com.eascs.crm.common.entity.CareerInfo;
import com.eascs.crm.common.entity.CreditRecordDetail;
import com.eascs.crm.common.entity.GuaranteeInfo;
import com.eascs.crm.common.entity.LoanInfo;
import com.eascs.crm.common.entity.ResidentialInfo;
import com.eascs.crm.common.entity.SemiCreditCardInfo;
import com.eascs.crm.common.service.ICustomerInfoService;
import com.eascs.crm.common.vo.Credit;
import com.eascs.crm.common.vo.DebitCardInfo1;
import com.eascs.datalist.dao.O2oDataListDao;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.workflow.form.CreditForm;
import com.eascs.workflow.util.CreditTransforCreditFrom;

/**
 * 征信解析Service
 * 
 * @author ycz
 *
 */
@Service
public class CreditResolveService {
	private static Logger logger = LoggerFactory.getLogger(CreditResolveService.class);
	@Autowired
	private O2oCreditDao creditDao;
	@Autowired
	private OaDatalistDao oaDataListDao;
	@Autowired
	private O2oLoanUserDao loanDao;
	@Autowired
	private O2oDataListDao o2oDataListDao;
	@Reference
	private ICustomerInfoService iCustomerInfoService;

	public void saveAttch() {
		int count = 0;
		List<CreditResolve> creditResolveList = creditDao.queryBillCode();
		for (CreditResolve creditResolve : creditResolveList) {
			logger.info("查询借款信息：单号[{}],loanapplyNo:[{}],loanId:[{}],urlpath:[{}]", creditResolve.getBillCode(), creditResolve.getLoanapplyNo(), creditResolve.getLoanId(), creditResolve.getUrl());
			try {
				if (!creditResolve.getBillCode().startsWith("O2O")) {
					creditResolve.setParentId("0");
					creditDao.insert(creditResolve);
					logger.info("插入新借款信息:{}", creditResolve.toString());
				} else {
					CreditResolve mainCreditResolve=null;
					try {
						mainCreditResolve= oaDataListDao.findUrl(creditResolve.getLoanId());
					} catch (Exception e) {
						logger.info("老系统查询异常：【{}】", e.getMessage());
					}
					if (mainCreditResolve != null) {
						creditResolve.setUrl(mainCreditResolve.getUrl());
						creditResolve.setParentId("0");
						creditDao.insert(creditResolve);
					}else{
						creditResolve.setParentId("0");
						creditDao.insert(creditResolve);
					}
					logger.info("插入老系统主借款信息:[{}]", creditResolve.toString());
				}
				O2oLoanUserEntity spouseEntity = loanDao.findSpouseId(creditResolve.getLoanId(), creditResolve.getLoanapplyNo());
				if (spouseEntity != null) {
					if (creditResolve.getBillCode().startsWith("O2O")) {
						CreditResolve spouseCreditResolve=null;
						try {
							 spouseCreditResolve = oaDataListDao.findUrl(spouseEntity.getLoanId());
						} catch (Exception e) {
							logger.error("老系统查询异常：【{}】", spouseCreditResolve.toString());
						}
						if (spouseCreditResolve != null) {
							logger.info("老系统配偶征信URL：[{}]", spouseCreditResolve.getUrl());
							CreditResolve spouseCredit = new CreditResolve();
							spouseCredit.setBillCode(creditResolve.getBillCode());
							spouseCredit.setLoanId(spouseEntity.getLoanId());
							spouseCredit.setUrl(spouseCreditResolve.getUrl());
							spouseCredit.setLoanapplyNo(creditResolve.getLoanapplyNo());
							spouseCredit.setParentId(creditResolve.getId());
							spouseCredit.setCustomerName(spouseEntity.getCustomerName());
							creditDao.insert(spouseCredit);
						}else{
							CreditResolve spouseCredit = new CreditResolve();
							spouseCredit.setBillCode(creditResolve.getBillCode());
							spouseCredit.setLoanId(spouseEntity.getLoanId());
							spouseCredit.setLoanapplyNo(creditResolve.getLoanapplyNo());
							spouseCredit.setParentId(creditResolve.getId());
							spouseCredit.setCustomerName(spouseEntity.getCustomerName());
							creditDao.insert(spouseCredit);
						}
					} else {
						O2oDataListEntity o2oDataEntity = o2oDataListDao.findCode(creditResolve.getLoanapplyNo(), StatusContexts.ZX_SPOUSE_CODE);
						if (o2oDataEntity != null) {
							CreditResolve spouseCredit = new CreditResolve();
							spouseCredit.setLoanapplyNo(creditResolve.getLoanapplyNo());
							spouseCredit.setLoanId(spouseEntity.getLoanId());
							spouseCredit.setParentId(creditResolve.getId());
							spouseCredit.setUrl(o2oDataEntity.getUrlpath());
							spouseCredit.setBillCode(creditResolve.getBillCode());
							spouseCredit.setCustomerName(spouseEntity.getCustomerName());
							creditDao.insert(spouseCredit);
						}
					}
				}
				count++;
			} catch (Exception e) {
				logger.info("单号：[{}],异常原因:[{}]", creditResolve.getBillCode(), e.getMessage());
			}
		}
		logger.info("插入借款信息次数：[{}]", count);
		//resolveCredit();
	}

	public void resolveCredit() {
		String sql = "SELECT * FROM O2O_CREDIT_RESOLVE T WHERE T.AGE=0 AND CONTRACT_TOTAL IS NULL";
		List<CreditResolve> creditResolveList = creditDao.findEntitys(sql, CreditResolve.class);
		for (CreditResolve resolve : creditResolveList) {
			try {
			//logger.info("开始解析征信报告：loanId[{}],url:[{}]", resolve.getLoanId(), resolve.getUrl());
			Credit credit = iCustomerInfoService.getCustomerInquiry(resolve.getLoanId(), resolve.getUrl());
			if (credit != null) {
				logger.info("征信解析成功,Credit：[{}]", credit.toString());
				CreditForm creditForm = this.getCreditReportEntity(credit);
				CreditReport report = new CreditReport();
				if(null !=credit.getIdentityInfo()){
					if(credit.getIdentityInfo().getBirthday()!=null){
						int count=DateUtils.getYear(credit.getIdentityInfo().getBirthday());
						int age=2017-count;
						resolve.setAge(age);
						logger.info("年龄:[{}]", resolve.getAge());
					}
					if(credit.getResidentialInfoList()!=null && credit.getResidentialInfoList().size()>0){
						ResidentialInfo info =credit.getResidentialInfoList().get(credit.getResidentialInfoList().size()-1);
						resolve.setHomeNum(String.valueOf(info.getNum()));
						//logger.info("家庭编号：[{}]", resolve.getHomeNum());
					}
					if(credit.getCareerInfoList()!=null && credit.getCareerInfoList().size()>0){
						CareerInfo info=credit.getCareerInfoList().get(credit.getCareerInfoList().size()-1);
						resolve.setWorkNum(String.valueOf(info.getNum()));
						//logger.info("工作编号：[{}]", resolve.getWorkNum());
					}
					resolve.setSex(credit.getIdentityInfo().getSex());
					resolve.setMaritalStatus(credit.getIdentityInfo().getMarital_status());
					resolve.setEducation(credit.getIdentityInfo().getEducation());
				}
				CreditTransforCreditFrom.saveCreditReport(report, creditForm);
					resolve.setAssureBalance(report.getAssureBalance());
					resolve.setAssureStatus(report.getAssureStatus());
					resolve.setAssureTotal(report.getAssureTotal());
					resolve.setAvgCardusedAmt(report.getAvgCardusedAmt());
					resolve.setAvgmonthRepayCar(report.getAvgmonthRepayCar());
					resolve.setAvgmonthRepayHouse(report.getAvgmonthRepayHouse());
					resolve.setBankBalanceOverdue(report.getBankBalanceOverdue());
					resolve.setBankPaymentBalance(report.getBankPaymentBalance());
					resolve.setContractTotal(report.getContractTotal());
					resolve.setContractTotalOverdue(report.getContractTotalOverdue());
					resolve.setCreditBalance(report.getCreditBalance());
					resolve.setCreditCount(report.getCreditCount());
					resolve.setCreditLimitOverdue(report.getCreditLimitOverdue());
					resolve.setCreditLimitRate(report.getCreditLimitRate());
					resolve.setCreditPaymentBalance(report.getCreditPaymentBalance());
					resolve.setCreditSearch(report.getCreditSearch());
					resolve.setImpawnPaymentBalance(report.getImpawnPaymentBalance());
					resolve.setMortgageCar(report.getMortgageCar());
					resolve.setMortgageCarBalance(report.getMortgageCarBalance());
					resolve.setMortgageHouse(report.getMortgageHouse());
					resolve.setMortgageHouseBalance(report.getMortgageHouseBalance());
					resolve.setNonbankBalanceOverdue(report.getNonbankBalanceOverdue());
					resolve.setNonbankPaymentBalance(report.getNonbankPaymentBalance());
					resolve.setOutAssureBalance(report.getOutAssureBalance());
					resolve.setOutAssureBalanceOverdue(report.getOutAssureBalanceOverdue());
					resolve.setOutAssureCount(report.getOutAssureCount());
					resolve.setPaymentBalance(report.getPaymentBalance());
					resolve.setPledgePaymentBalance(report.getPledgePaymentBalance());
					this.updateCreditResolve(resolve);
			} else {
				logger.info("征信解析失败,单号：[{}]", resolve.getBillCode());
			}
			} catch (Exception e) {
				logger.info("异常单号：[{}],解析接口异常原因：[{}]", resolve.getBillCode(),e.getMessage());
			}
		}

	}

	private void updateCreditResolve(CreditResolve resolve) {
		try {
			int flag = creditDao.updateById(resolve);
			if (flag > 0) {
				logger.info("单号：[{}]修改成功", resolve.getBillCode());
			} else {
				logger.info("单号：[{}]修改失败", resolve.getBillCode());
			}
		} catch (Exception e) {
			logger.info("修改贷款异常单号：[{}]", e.getMessage());
		}
	}

	/**
	 * 构建CreditForm实体
	 * 
	 * @param credit
	 * @param code
	 * @return
	 */
	private CreditForm getCreditReportEntity(Credit credit) {
		CreditForm creditForm = new CreditForm();
		BigDecimal contractTotal = BigDecimal.ZERO;// 贷款合同总额
		BigDecimal bankBalanceOverdue = BigDecimal.ZERO;// 银行机构逾期W1：机构类型显示为银行的当前逾期金额之和
		Integer mortgageHouse = 0;// 住房按揭数 B
		BigDecimal mortgageHouseBalance = BigDecimal.ZERO;// 住房按揭贷款余额 C
		BigDecimal avgmonthRepayHouse = BigDecimal.ZERO;// 住房月均还款额 D
		Integer mortgageCar = 0;// 按揭车辆数 E
		BigDecimal mortgageCarBalance = BigDecimal.ZERO;// 车辆按揭贷款余额F
		BigDecimal avgmonthRepayCar = BigDecimal.ZERO;// 车辆月均还款额G
		BigDecimal creditPaymentBalance = BigDecimal.ZERO;// 信用（含保证）贷款余额H:贷款种类为个人消费贷款、个人经营性贷款、农户贷款、其他；机构类型为：银行；担保方式：信用/免担保、自然人保证、其他、农户联保的本金余额之和
		BigDecimal pledgePaymentBalance = BigDecimal.ZERO;// 抵押贷款余额I:贷款种类为个人消费贷款、个人经营性贷款、农户贷款、其他；机构类型为银行；担保方式为抵押的本金余额之和
		BigDecimal impawnPaymentBalance = BigDecimal.ZERO;// 质押贷款余额J:贷款种类为个人消费贷款、个人经营性贷款、农户贷款、其他；机构类型为银行；担保方式为质押的本金余额之和
		BigDecimal groupAssureBalance = BigDecimal.ZERO;// 组合担保贷款余额K:贷款种类为个人消费贷款、个人经营性贷款、农户贷款、其他；机构类型为：银行；担保方式为组合的本金余额之和
		Integer creditCount = 0;// 持有信用卡张数 M
		BigDecimal creditBalance = BigDecimal.ZERO;// 授信余总额 N
		BigDecimal avgCardusedAmt = BigDecimal.ZERO;// 信用卡最近6个月平均透支额度 O
		BigDecimal creditLimitRate = BigDecimal.ZERO;// 信用卡透支（逾期）P
		BigDecimal creditLimitOverdue = BigDecimal.ZERO;// 信用卡逾期 W3
		BigDecimal nonbankPaymentBalance = BigDecimal.ZERO;// 非银行机构贷款余额L：机构类型为消费金融有限公司、小额贷款公司、信托机构、财务公司的本金余额之和
		BigDecimal nonbankBalanceOverdue = BigDecimal.ZERO;// 非银行机构逾期W2:机构类型为消费金融有限公司、小额贷款公司、信托机构、财务公司的当前逾期金额之和
		Integer outAssureCount = 0;// 担保笔数 Q
		BigDecimal assureTotal = BigDecimal.ZERO;// 担保总额 R
		BigDecimal assureBalance = BigDecimal.ZERO;// 担保余额 S
		Integer creditSearch = 0;// 信用卡、贷款审批查询次数 T
		if (null != credit.getCreditSummary()) {
			logger.info("按揭房产解析：CreditSummary【{}】", credit.getCreditSummary());
			mortgageHouse = IntegerToZero(credit.getCreditSummary().getSell_house_num() + // 按揭房产：_B_套
					IntegerToZero(credit.getCreditSummary().getBisness_house_num()));
		}
		if (null != credit.getLoanInfoList() && !credit.getLoanInfoList().isEmpty()) {
			for (LoanInfo loanInfo : credit.getLoanInfoList()) {
				if (loanInfo.getLoan_type() != null && loanInfo.getLoan_type().contains(StatusContexts.ZX_HOUSE_TYPE)) {// 住房按揭
					mortgageHouseBalance = BigDecimalToZero(loanInfo.getPrincipal_balance()).add(mortgageHouseBalance);// 住房按揭贷款余额C
					avgmonthRepayHouse = BigDecimalToZero(loanInfo.getRepayment_this_month()).add(avgmonthRepayHouse);// 住房月均还款额D
				} else if (loanInfo.getLoan_type() != null && loanInfo.getLoan_type().contains(StatusContexts.ZX_CAR_TYPE)) {// 车辆按揭
					mortgageCar++;// 按揭车辆数 E
					mortgageCarBalance = BigDecimalToZero(loanInfo.getPrincipal_balance()).add(mortgageCarBalance);// 车辆按揭贷款余额F
					avgmonthRepayCar = BigDecimalToZero(loanInfo.getRepayment_this_month()).add(avgmonthRepayCar);// 车辆月均还款额G
				} else {
					if (loanInfo.getInstitution_type() != null && loanInfo.getInstitution_type().contains(StatusContexts.ZX_BANK_TYPE)) {// 机构类型为：商业银行
						if (loanInfo.getGuarantee_way() != null && loanInfo.getGuarantee_way().contains(StatusContexts.ZX_MORTGAGE_TYPE)) {
							pledgePaymentBalance = BigDecimalToZero(loanInfo.getPrincipal_balance()).add(pledgePaymentBalance);// 抵押贷款余额I
						} else if (loanInfo.getGuarantee_way() != null && loanInfo.getGuarantee_way().contains(StatusContexts.ZX_PLEDGE_TYPE)) {
							impawnPaymentBalance = BigDecimalToZero(loanInfo.getPrincipal_balance()).add(impawnPaymentBalance);// 质押贷款余额J
						} else if (loanInfo.getGuarantee_way() != null && loanInfo.getGuarantee_way().contains(StatusContexts.ZX_GROUP_TYPE)) {
							groupAssureBalance = BigDecimalToZero(loanInfo.getPrincipal_balance()).add(groupAssureBalance);// 组合担保贷款余额K
						} else {
							creditPaymentBalance = BigDecimalToZero(loanInfo.getPrincipal_balance()).add(creditPaymentBalance);// 信用（含保证）贷款余额H
						}
					} else {
						nonbankPaymentBalance = BigDecimalToZero(loanInfo.getPrincipal_balance()).add(nonbankPaymentBalance);// 非银行机构贷款余额L
						nonbankBalanceOverdue = BigDecimalToZero(loanInfo.getCurrent_period_amount()).add(nonbankBalanceOverdue);// 非银行机构逾期W2
					}
				}
				if (loanInfo.getInstitution_type() != null && loanInfo.getInstitution_type().contains(StatusContexts.ZX_BANK_TYPE)) {// 银行机构逾期
																																		// W1：机构类型显示为银行的当前逾期金额之和
					bankBalanceOverdue = BigDecimalToZero(loanInfo.getCurrent_period_amount()).add(bankBalanceOverdue);
				}
			}
		}
		// 未销户贷记卡信息汇总
		if (null != credit.getUnDebitSummary()) {
			creditCount = credit.getUnDebitSummary().getCard_corporate_num() + creditCount;// 持有信用卡张数M
			creditBalance = BigDecimalToZero(credit.getUnDebitSummary().getTotal_credit()).add(creditBalance);// 授信余总额N
			avgCardusedAmt = BigDecimalToZero(credit.getUnDebitSummary().getSix_average_amount()).add(avgCardusedAmt);// 信用卡最近6个月平均透支额度
																														// O
			creditLimitRate = BigDecimalToZero(credit.getUnDebitSummary().getUse_amount()).add(creditLimitRate);// 信用卡透支（逾期）P
		}
		// 未销户准贷记卡信息汇总
		if (null != credit.getUnZdebitSummary()) {
			creditCount = credit.getUnZdebitSummary().getCard_corporate_num() + creditCount;// 持有信用卡张数M
			creditBalance = BigDecimalToZero(credit.getUnZdebitSummary().getTotal_credit()).add(creditBalance);// 授信余总额N
			avgCardusedAmt = BigDecimalToZero(credit.getUnZdebitSummary().getSix_average_amount()).add(avgCardusedAmt);// 信用卡最近6个月平均透支额度O
			creditLimitRate = BigDecimalToZero(credit.getUnZdebitSummary().getUse_amount()).add(creditLimitRate);// 信用卡透支（逾期）P
		}
		// 贷记卡
		if (null != credit.getDebitCardInfo1List() && !credit.getDebitCardInfo1List().isEmpty()) {
			for (DebitCardInfo1 debitCardInfo : credit.getDebitCardInfo1List()) {// 信用卡逾期W3
				creditLimitOverdue = BigDecimalToZero(debitCardInfo.getCurrent_period_amount()).add(creditLimitOverdue);
			}
		}
		// 准贷记卡
		if (null != credit.getSemiCreditCardInfoList() && !credit.getSemiCreditCardInfoList().isEmpty()) {
			for (SemiCreditCardInfo semiCreditCardInfo : credit.getSemiCreditCardInfoList()) {// 信用卡逾期W3
				creditLimitOverdue = BigDecimalToZero(semiCreditCardInfo.getOutstanding_balance()).add(creditLimitOverdue);
			}
		}
		// 担保信息
		if (null != credit.getGuaranteeInfoList() && !credit.getGuaranteeInfoList().isEmpty()) {
			outAssureCount = credit.getGuaranteeInfoList().size();// 担保笔数 Q
			for (GuaranteeInfo guaranteeInfo : credit.getGuaranteeInfoList()) {
				assureTotal = BigDecimalToZero(guaranteeInfo.getContract_amount()).add(assureTotal);// 担保总额R
				assureBalance = BigDecimalToZero(guaranteeInfo.getPrincipal_balance()).add(assureBalance);// 担保余额S
			}
		}
		// 信用卡、贷款审批查询次数T 日期可以直接用当前日期处理即可
		if (null != credit.getCreditRecordDetailList() && !credit.getCreditRecordDetailList().isEmpty()) {// 信用卡、贷款审批查询次数T
			Date dateMonth = DateUtils.addMonth(new Date(), -2);
			for (CreditRecordDetail creditRecordDetail : credit.getCreditRecordDetailList()) {
				if (dateMonth.getTime() <= creditRecordDetail.getQuery_date().getTime() && creditRecordDetail.getQuery_date().getTime() <= new Date().getTime()) {
					creditSearch++;
				}
			}
		}
		// 征信总额 A
		contractTotal = creditBalance;
		// 未结清贷款信息汇总
		if (null != credit.getUnLoaninfoSummary()) {// 未结清贷款信息汇总 A
			contractTotal = BigDecimalToZero(credit.getUnLoaninfoSummary().getTotal_amount()).add(creditBalance);
		}
		creditForm.setMortgageHouse(mortgageHouse);
		creditForm.setContractTotal(contractTotal.doubleValue());
		creditForm.setBankBalanceOverdue(bankBalanceOverdue.doubleValue());
		creditForm.setMortgageHouseBalance(mortgageHouseBalance.doubleValue());
		creditForm.setAvgmonthRepayHouse(avgmonthRepayHouse.doubleValue());
		creditForm.setMortgageCar(mortgageCar);
		creditForm.setMortgageCarBalance(mortgageCarBalance.doubleValue());
		creditForm.setAvgmonthRepayCar(avgmonthRepayCar.doubleValue());
		creditForm.setCreditPaymentBalance(creditPaymentBalance.doubleValue());
		creditForm.setPledgePaymentBalance(pledgePaymentBalance.doubleValue());
		creditForm.setImpawnPaymentBalance(impawnPaymentBalance.doubleValue());
		creditForm.setGroupAssureBalance(groupAssureBalance.doubleValue());
		creditForm.setCreditCount(creditCount);
		creditForm.setCreditBalance(creditBalance.doubleValue());
		creditForm.setAvgCardusedAmt(avgCardusedAmt.doubleValue());
		creditForm.setCreditLimitRate(creditLimitRate.doubleValue());
		creditForm.setCreditLimitOverdue(creditLimitOverdue.doubleValue());
		creditForm.setNonbankPaymentBalance(nonbankPaymentBalance.doubleValue());
		creditForm.setNonbankBalanceOverdue(nonbankBalanceOverdue.doubleValue());
		creditForm.setOutAssureCount(outAssureCount);
		creditForm.setAssureTotal(assureTotal.doubleValue());
		creditForm.setAssureBalance(assureBalance.doubleValue());
		creditForm.setCreditSearch(creditSearch);
		return creditForm;
	}

	/**
	 * Integer 为空值转成0
	 * 
	 * @param decimal
	 * @return
	 */
	public Integer IntegerToZero(Integer decimal) {
		if (decimal == null) {
			decimal = 0;
		}
		return decimal;
	}

	/**
	 * BigDecimal空值处理转换单位为万元
	 * 
	 * @return
	 */
	public BigDecimal BigDecimalToZero(BigDecimal decimal) {
		if (decimal == null) {
			decimal = BigDecimal.ZERO;
		} else {
			BigDecimal count = new BigDecimal(10000);
			decimal = decimal.divide(count, 4, RoundingMode.HALF_UP);
		}
		return decimal;
	}
}
